import React, { useState, useEffect } from 'react';
import { Languages, Volume2, Copy, RotateCcw, Loader, X } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
// 我们将在CSS文件中添加更详细的样式
import '@/pages/translation.css';

const TranslationPage: React.FC = () => {
  const [sourceText, setSourceText] = useState('');
  const [translatedText, setTranslatedText] = useState('');
  const [sourceLang, setSourceLang] = useState('zh');
  const [targetLang, setTargetLang] = useState('en');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [history, setHistory] = useState<string[]>([]);
  const navigate = useNavigate();

  // 支持的语言列表
  const languages = [
    { code: 'zh', name: '中文' },
    { code: 'en', name: 'English' },
    { code: 'ja', name: '日本語' },
    { code: 'ko', name: '한국어' },
    { code: 'fr', name: 'Français' },
    { code: 'de', name: 'Deutsch' },
    { code: 'es', name: 'Español' },
    { code: 'it', name: 'Italiano' },
    { code: 'ru', name: 'Русский' },
    { code: 'ar', name: 'العربية' },
  ];

  // 处理翻译请求
  const handleTranslate = async () => {
    if (!sourceText.trim()) return;

    setIsLoading(true);
    setError(null);

    try {
      // 调用翻译API
      const response = await fetch('https://api.mymultilingualapp.com/translate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          text: sourceText,
          from: sourceLang,
          to: targetLang
        }),
      });

      if (!response.ok) {
        throw new Error(`翻译服务暂时不可用: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      if (!data.translatedText) {
        throw new Error('未获取到翻译结果');
      }
      setTranslatedText(data.translatedText);

      // 添加到历史记录
      if (history.length >= 5) {
        setHistory([...history.slice(1), sourceText]);
      } else {
        setHistory([...history, sourceText]);
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '翻译失败，请重试';
      setError(errorMessage);
      console.error('翻译错误:', err);
    } finally {
      setIsLoading(false);
    }
  };

  // 交换语言
  const handleSwapLanguages = () => {
    setSourceLang(targetLang);
    setTargetLang(sourceLang);
    if (translatedText) {
      setSourceText(translatedText.replace(/\[.*?\] /, ''));
      setTranslatedText(sourceText);
    }
  };

  // 复制到剪贴板
  const handleCopy = () => {
    if (translatedText) {
      navigator.clipboard.writeText(translatedText);
      // 可以添加一个复制成功的提示
    }
  };

  // 语音朗读
  const handleSpeak = (text: string, lang: string) => {
    if ('speechSynthesis' in window) {
      const utterance = new SpeechSynthesisUtterance(text);
      utterance.lang = lang;
      window.speechSynthesis.speak(utterance);
    }
  };

  // 清除错误
  const clearError = () => {
    setError(null);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50 py-8">
      <div className="container mx-auto px-4 max-w-6xl">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-2xl md:text-3xl font-bold text-gray-900">实时翻译</h1>
          <button 
            onClick={() => navigate('/')}
            className="text-gray-600 hover:text-gray-900 transition-colors"
            aria-label="返回首页"
          >
            <X size={24} />
          </button>
        </div>
        {error && (
          <div className="error-message animate-fade-in">
            <span>{error}</span>
            <button onClick={clearError} className="error-close-button">
              <X size={18} />
            </button>
          </div>
        )}

        <div className="translation-container animate-fade-in">
          <div className="language-selector">
            <select
              value={sourceLang}
              onChange={(e) => setSourceLang(e.target.value)}
              className="language-select"
            >
              {languages.map((lang) => (
                <option key={lang.code} value={lang.code}>
                  {lang.name}
                </option>
              ))}
            </select>

            <button
              onClick={handleSwapLanguages}
              className="swap-button"
              aria-label="交换语言"
            >
              <RotateCcw size={20} />
              <span className="ml-2 hidden sm:inline">交换语言</span>
            </button>

            <select
              value={targetLang}
              onChange={(e) => setTargetLang(e.target.value)}
              className="language-select"
            >
              {languages.map((lang) => (
                <option key={lang.code} value={lang.code}>
                  {lang.name}
                </option>
              ))}
            </select>
          </div>

          <div className="translation-grid mt-6">
            <div className="text-area-container">
              <textarea
                value={sourceText}
                onChange={(e) => setSourceText(e.target.value)}
                placeholder="请输入要翻译的文本..."
                className="text-area"
              ></textarea>
              <div className="action-buttons">
                <button
                  onClick={() => handleSpeak(sourceText, sourceLang)}
                  className="action-button"
                  aria-label="朗读原文"
                >
                  <Volume2 size={18} />
                  <span className="hidden sm:inline">朗读</span>
                </button>
              </div>
            </div>

            <div className="text-area-container">
              <textarea
                value={translatedText}
                readOnly
                placeholder="翻译结果..."
                className="text-area bg-gray-50"
              ></textarea>
              <div className="action-buttons">
                <button
                  onClick={() => handleSpeak(translatedText, targetLang)}
                  className="action-button"
                  aria-label="朗读译文"
                >
                  <Volume2 size={18} />
                  <span className="hidden sm:inline">朗读</span>
                </button>
                <button
                  onClick={handleCopy}
                  className="action-button"
                  aria-label="复制译文"
                >
                  <Copy size={18} />
                  <span className="hidden sm:inline">复制</span>
                </button>
              </div>
            </div>
          </div>

          <button
            onClick={handleTranslate}
            className="translate-button"
            disabled={isLoading || !sourceText.trim()}
          >
            {isLoading ? (
              <>{<Loader size={18} className="loading-spinner" />} 翻译中...</>
            ) : (
              <>{<Languages size={18} />} 翻译</>
            )}
          </button>
        </div>

        {history.length > 0 && (
          <div className="history-container mt-6 animate-fade-in">
            <h3 className="history-title">翻译历史</h3>
            <ul className="history-list">
              {history.map((item, index) => (
                <li
                  key={index}
                  className="history-item"
                  onClick={() => setSourceText(item)}
                >
                  {item}
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
};

// 添加简单的动画效果
const styles = `
  @keyframes fade-in {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
  }
  .animate-fade-in {
    animation: fade-in 0.3s ease-out forwards;
  }
`;

// 将样式添加到文档头部
if (typeof document !== 'undefined') {
  const styleElement = document.createElement('style');
  styleElement.textContent = styles;
  document.head.appendChild(styleElement);
}

export default TranslationPage;